// global variables as cache
var thoughts;
var goals;
var sharedThoughts;

//TODO: authenticated user
var owner_id = 1;

function wlCommonInit(){
	registerEvents();	
	jq.mobile.changePage("#Category_ThoughtsListPage");
}

/**
 * General functions
 */
function showErrorMessage(text){
	jq.mobile.hidePageLoadingMsg();
	jq("#errorMsg").html(text);
	jq.mobile.changePage("#ErrorMsgDialog");
}

function loadItemsFail(data){
	WL.Logger.debug("Items::load failed");
	jq.mobile.hidePageLoadingMsg();
	showErrorMessage(data.errorMsg);
}


/********************************************************************
 * Load thoughts & Display them
 */
function loadThoughts(owner_id){
	WL.Logger.debug("Thoughts::load thoughts");
	jq.mobile.showPageLoadingMsg();

	var thoughtsInvocationData = {
			adapter: "DataControllerAdaptor",
			procedure: "listThoughts",
			parameters: [owner_id]
	};
	
	WL.Client.invokeProcedure(thoughtsInvocationData, {
		onSuccess: loadThoughtsSuccess, 
		onFailure: loadItemsFail
	});
}


function loadThoughtsSuccess(data){
	WL.Logger.debug("Items::load successfully");
	if (!data || !data.invocationResult || !data.invocationResult.resultSet || data.invocationResult.resultSet.length==0)
		showErrorMessage("Could not retrieve correct data from server");
	
	thoughts = data.invocationResult.resultSet;
	displayThoughts(thoughts)
}


function displayThoughts(thoughts){
	jq("#ThoughtsList").empty();
	
	var markup = "<li data-role='list-divider'> ${update_date} <span class='ui-li-count'>${shared}</span></li>" +
			"<li><a href='#Content_ThoughtPage?id=${id}'> <h3></h3>" +
			"<p><strong>${thought}</strong></p> <p>${action}</p></a>"+
			"<a href='#ModifyDialog' data-role='button' data-inline='true' data-rel='dialog' data-transition='slidedown'>编辑记录</a></li>";

	// Compile the markup as a named template
	jq.template( "listTemplate", markup );
	// Render the template with the thougths data
	jq.tmpl( "listTemplate", thoughts ).appendTo( "#ThoughtsList" );
	
	jq("#ThoughtsList").listview('refresh');
	jq.mobile.hidePageLoadingMsg();
}

/********************************************************************
 * Load goals and display goal
 */
function loadGoals(owner_id){
	WL.Logger.debug("Goals::load goals");
	jq.mobile.showPageLoadingMsg();

	var goalsInvocationData = {
			adapter: "DataControllerAdaptor",
			procedure: "listGoals",
			parameters: [owner_id]
	};
	
	WL.Client.invokeProcedure(goalsInvocationData, {
		onSuccess: loadGoalsSuccess, 
		onFailure: loadItemsFail
	});
}


function loadGoalsSuccess(data){
	WL.Logger.debug("Goals::load successfully");
	if (!data || !data.invocationResult || !data.invocationResult.resultSet || data.invocationResult.resultSet.length==0)
		showErrorMessage("Could not retrieve correct data from server");
	
	goals = data.invocationResult.resultSet;
	displayGoals(goals);
}

function displayGoals(goals){
	jq("#GoalsList").empty();
	
	var markup = "<li data-role='list-divider'> ${update_year} </li>" +
			"<li><a href='#Content_GoalPage?id=${id}'> <h3></h3>" +
			"<p><strong>${goal}</strong></p> <p>${action}</p></a></li>";

	// Compile the makeup as a named template
	jq.template( "listTemplate", markup );
	// Render the template with the goals
	jq.tmpl( "listTemplate", goals).appendTo( "#GoalsList" );
	
	jq("#GoalsList").listview('refresh');
	jq.mobile.hidePageLoadingMsg();
}


/********************************************************************
 * Load shared thoughts and display them
 */
function loadSharedThoughts(){
	WL.Logger.debug("Thoughts::load shared thoughts");
	jq.mobile.showPageLoadingMsg();

	var thoughtsInvocationData = {
			adapter: "DataControllerAdaptor",
			procedure: "listSharedThoughts",
			parameters: []
	};
	
	WL.Client.invokeProcedure(thoughtsInvocationData, {
		onSuccess: loadSharedThoughtsSuccess, 
		onFailure: loadItemsFail
	});
}


function loadSharedThoughtsSuccess(data){
	WL.Logger.debug("Thoughts::load shard thoughts successfully");
	if (!data || !data.invocationResult || !data.invocationResult.resultSet || data.invocationResult.resultSet.length==0)
		showErrorMessage("Could not retrieve correct data from server");
	
	sharedThoughts = data.invocationResult.resultSet;
	displaySharedThoughts(sharedThoughts)
}


function displaySharedThoughts(sharedThoughts){
	jq("#SharedThoughtsList").empty();
	
	var markup = "<li data-role='list-divider'> ${update_date} </li>" +
			"<li><a href='#Content_SharedThoughtPage?id=${id}'> <h3></h3>" +
			"<p><strong>${thought}</strong></p> <p>${action}</p></a></li>";
	
	// Compile the makeup as a named template
	jq.template( "listTemplate", markup );
	// Render the template with the thoughts
	jq.tmpl( "listTemplate", sharedThoughts ).appendTo( "#SharedThoughtsList" );
	
	jq("#SharedThoughtsList").listview('refresh');
	jq.mobile.hidePageLoadingMsg();
}


// Search record in cache
function searchGoal(id){
	if(goals){
		for(var i=0;i<goals.length;i++){
			if(goals[i].id==id){
				return goals[i];
			}
		}
	}
	showErrorMessage("记录（"+id+"）不存在！");
}

function searchThought(id){
	if(thoughts){
		for(var i=0;i<thoughts.length;i++){
			if(thoughts[i].id==id){
				return thoughts[i];
			}
		}
	}
	showErrorMessage("记录（"+id+"）不存在！");
}

function searchSharedThought(id){
	if(sharedThoughts){
		for(var i=0;i<sharedThoughts.length;i++){
			if(sharedThoughts[i].id==id){
				return sharedThoughts[i];
			}
		}
	}
	showErrorMessage("记录（"+id+"）不存在！");
}
